package com.gs.SynAntiWandering.activity;

import android.Manifest;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Build;
import android.os.Bundle;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;

import com.gs.SynAntiWandering.R;
import com.gs.SynAntiWandering.activity.base.BaseFragmentActivity;
import com.gs.SynAntiWandering.apiresult.ApiResultData;
import com.gs.SynAntiWandering.constant.AllConstants;
import com.gs.SynAntiWandering.db.dao.DBUtil;
import com.gs.SynAntiWandering.db.dto.VersionDto;
import com.gs.SynAntiWandering.dialog.CommDialogUtils;
import com.gs.SynAntiWandering.fragment.AlertFragment;
import com.gs.SynAntiWandering.fragment.InsightFragment;
import com.gs.SynAntiWandering.fragment.MemberFragment;
import com.gs.SynAntiWandering.fragment.RecordFragment;
import com.gs.SynAntiWandering.fragment.SettingsFragment;
import com.gs.SynAntiWandering.presenter.MainPresenter;
import com.gs.SynAntiWandering.receiver.NetworkBroadcastReceiver;
import com.gs.SynAntiWandering.service.CloseService;
import com.gs.SynAntiWandering.util.AppUtil;
import com.gs.SynAntiWandering.util.PermissionUtil;
import com.gs.SynAntiWandering.util.ToastUtil;
import com.gs.SynAntiWandering.view.IMainView;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

public class MainActivity extends BaseFragmentActivity implements IMainView {

    private List<Fragment> fragmentList;
    private Fragment mFragment;
    private int fragmentIndex;
    private MainPresenter mPresenter;
    private NetworkBroadcastReceiver receiver;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_main;
    }

    @Override
    protected void initView(Bundle savedInstanceState) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O_MR1) {
            setShowWhenLocked(true);
        } else {
            Window window = getWindow();
            window.addFlags(WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED
                    | WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD);
        }
        OnClickListener onClickListener = new OnClickListener();
        fd(R.id.tv_insight).setOnClickListener(onClickListener);
        fd(R.id.tv_report).setOnClickListener(onClickListener);
        fd(R.id.tv_alert).setOnClickListener(onClickListener);
        fd(R.id.tv_settings).setOnClickListener(onClickListener);
        fd(R.id.tv_member).setOnClickListener(onClickListener);
        if (savedInstanceState != null) {
            fragmentIndex = savedInstanceState.getInt(AllConstants.WHAT);
        } else {
            int what = getIntent().getIntExtra(AllConstants.WHAT, 0);
            if (what == 2) {
                fragmentIndex = 2;
            }
//            else if (what == 1000) {
//                CommDialogUtils.showDialog(this, "", getString(R.string.login_set), new CommDialogUtils.DialogClickListener() {
//                    @Override
//                    public void cancelClick() {
//                    }
//
//                    @Override
//                    public void okClick() {
//                        PermissionUtil.gotoAutoActivity(MainActivity.this);
//                    }
//                });
//            }
        }
        showFragment(mFragment, getFragment());
        PermissionUtil.addPermission(this,
                new String[]{
                        Manifest.permission.REQUEST_INSTALL_PACKAGES,
                        Manifest.permission.FOREGROUND_SERVICE}, 1);
        mPresenter = new MainPresenter();
        mPresenter.attachView(this);
        if (fragmentIndex == 0) {
            registerReceiver();
            mPresenter.getVersion();
            startService(new Intent(this, CloseService.class));
            PermissionUtil.addNotifyPermission(this);
        }else if (fragmentIndex == 4){// 切换语言和项目时重新启动服务
            startService(new Intent(this, CloseService.class));
        }
    }

    private void registerReceiver() {
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction("android.net.conn.CONNECTIVITY_CHANGE");
        receiver = new NetworkBroadcastReceiver();
        registerReceiver(receiver, intentFilter);
    }

    @Override
    protected void initFragment() {
        fragmentList = new ArrayList<>();
        InsightFragment insightFragment = new InsightFragment();
        RecordFragment recordFragment = new RecordFragment();
        AlertFragment alertFragment = new AlertFragment();
        MemberFragment memberFragment = new MemberFragment();
        SettingsFragment settingsFragment = new SettingsFragment();
        fragmentList.add(insightFragment);
        fragmentList.add(recordFragment);
        fragmentList.add(alertFragment);
        fragmentList.add(memberFragment);
        fragmentList.add(settingsFragment);
    }

    /**
     * 刷新時清除舊的fragment
     */
    @Override
    public void recreate() {
        try {
            FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
            for (Fragment fragment : fragmentList) {
                ft.detach(fragment);
            }
            ft.commitAllowingStateLoss();
        } catch (Exception e) {
            e.printStackTrace();
        }
        super.recreate();
    }

    private Fragment getFragment() {
        return fragmentList.get(fragmentIndex);
    }

    private void showFragment(Fragment fromFragment, Fragment toFragment) {
        if (fromFragment != toFragment) {
            mFragment = toFragment;
            FragmentManager fm = getSupportFragmentManager();
            FragmentTransaction transaction = fm.beginTransaction();
            if (fromFragment != null) {
                transaction.hide(fromFragment);
            }
            if (toFragment.isAdded()) {
                transaction.show(toFragment);
            } else {
                transaction.add(R.id.fl_content, toFragment);
            }
            transaction.commit();
        }
    }

    @Override
    protected void onSaveInstanceState(@NonNull Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putInt(AllConstants.WHAT, fragmentIndex);
    }

    @Override
    public void onGetVersionSuccess(final ApiResultData<VersionDto> apiResultData) {
        if (apiResultData.getStatus() == 2000) {
            if (apiResultData.getData() != null) {
                int newVersion;
                int myVersion;
                try {
                    newVersion = Integer.parseInt(apiResultData.getData().getVersion().replace(".", ""));
                    myVersion = Integer.parseInt(AppUtil.getInstance().getVersion().replace(".", ""));
                } catch (NumberFormatException e) {
                    ToastUtil.showToast(R.string.version_error);
                    e.printStackTrace();
                    return;
                }
                if (newVersion > myVersion) {
                    CommDialogUtils.showDialog(MainActivity.this, getString(R.string.new_version),
                            apiResultData.getData().getDesc(), R.string.download,
                            new CommDialogUtils.DialogClickListener() {
                                @Override
                                public void cancelClick() {

                                }

                                @Override
                                public void okClick() {
                                    String fileName = apiResultData.getData().getOutputFile();
                                    File file = new File(MainActivity.this.getCacheDir(), fileName);
                                    if (file.exists()) file.delete();// 已下載過安裝包
                                    else file.getParentFile().mkdirs();
                                    // 展示進度條
                                    CommDialogUtils.showProgressDialog(MainActivity.this);
                                    mPresenter.downloadFile(fileName, file);
                                }
                            });
                }
            }
        }
    }

    @Override
    public void onGetVersionFails(Exception e) {

    }

    @Override
    public void onDownloadFileSuccess(File file) {
        AppUtil.getInstance().installApk(MainActivity.this, file);
        CommDialogUtils.dismissProDialog();
    }

    @Override
    public void onDownloadProgress(int progress) {
        CommDialogUtils.setProgress(progress);
    }

    @Override
    public void onDownloadFails(Exception e) {
        ToastUtil.showToast(R.string.download_error);
        CommDialogUtils.dismissProDialog();
    }

    class OnClickListener implements View.OnClickListener {

        @Override
        public void onClick(View v) {
            switch (v.getId()) {
                case R.id.tv_insight:
                    fragmentIndex = 0;
                    break;
                case R.id.tv_report:
                    fragmentIndex = 1;
                    break;
                case R.id.tv_alert:
                    fragmentIndex = 2;
                    break;
                case R.id.tv_member:
                    fragmentIndex = 3;
                    break;
                case R.id.tv_settings:
                    fragmentIndex = 4;
                    break;
            }
            showFragment(mFragment, getFragment());
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        DBUtil.getInstance().closeConnection();
        if (mPresenter != null) {
            mPresenter.detachView();
        }
        if (receiver != null) {
            unregisterReceiver(receiver);
        }
    }
}